#include <iostream>
#include <stdio.h>
#include <string>
#include <ctime>
#include <fstream>
#include "redcell.hpp"

using namespace std;
using namespace redcell;

void show(string s) {
  //ofstream ofs("marshal.dat");
  printf ("%d: ", s.size());
  for (string::iterator i=s.begin(); i!=s.end(); ++i) {
    printf("%02x ", (unsigned char)*i);
    //ofs.put(*i);
  }
  printf("\n");
  //ofs.close();
}

void test(bool echo) {
  Table tab;


  tab.i(0) = 123;
  tab.i(0) += 321;
  tab.s(1) = "hello";
  tab(6).i(9) = true;
  tab(5).r(8) = 3.141;

  tab.del(0);
  tab(5).nil(9);

  tab(11)(22)(33)(44)(55)(66).s(77) = "here i am";
  tab("aa")("bb")("cc").i("dd") = 1234;

  Table u;
  u.s(3) = "patch string";
  u(6).i(7) = false;
  u.r(1) = 1.;

  tab.merge(u);


  tab.r(0) = 3.141;

  if (echo) {
    cout << dump(tab) << endl;
  }

  //  u.gi(1111111);

  /*
  Variant u;
  u(0) = true;
  u(1) = 9999;
  u(2) = "xxxxxxxx";
  u(3) = 3.14f;
  u(5)(9) = 5.678;
  u(6)(9) = NIL;
  u->erase(1);

  if (echo) {
    cout << dump(v) << endl;
  }
  v.merge(u);

  if (echo) {
    cout << dump(v) << endl;
  }
  */

  string raw = pack(tab);

  if (echo) {
    show(raw);
  }

  Table w;

  w = unpack(raw);

  if (echo) {
    cout << dump(w) << endl;
  }
}

int main() {
  try {
    int echo = 1;
    int n = echo ? 1 : 500000;
    time_t t0 = time(NULL);
    for (int i=0; i<n; ++i) {
      test(echo);
    }
    time_t t1 = time(NULL);

    cout << (t1 - t0) << endl;
  } catch (Error &e) {
    cout << e.what() << endl;
  }

  return 0;
}
